package com.example.demo.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author star
 */
public class ObjectPropertyUtil {
    /**
     * 获取对象的非空属性名和属性值的集合
     */
    public static Map<String, Object> getNouNullPropertyMap(Object object) {
        Class<?> objectClass = object.getClass();
        Method[] methods = objectClass.getDeclaredMethods();
        HashMap<String, Object> map = new HashMap<>();
        for (Method method : methods) {
            try {
                String name = method.getName();
                if (name.startsWith("get")) {
                    Object value = method.invoke(object);
                    if (!ObjectUtil.isEmpty(value)) {
                        String column = StrUtil.toUnderlineCase(name.substring(3));
                        map.put(column,value);
                    }
                }
            } catch (Exception ignored) {
            }
        }
        return map;
    }
}
